﻿var grid;
var varIncrementer = 0;
var v_CollectionID = varIncrementer++,
        v_InvoiceID = varIncrementer++,
        v_Remarks = varIncrementer++,
        v_Sr = varIncrementer++,
        v_Action = varIncrementer++,
        v_CompanyName = varIncrementer++,
        v_ClientName = varIncrementer++,
        v_ContractName = varIncrementer++,
        v_InvoiceNo = varIncrementer++,
        v_CollectionNo = varIncrementer++,
        v_CollectionDate = varIncrementer++,
        v_CollectionType = varIncrementer++,
        v_DrawnOnBank = varIncrementer++,
        v_RefNo = varIncrementer++,
        v_Amount = varIncrementer++,
        v_TDSAmount = varIncrementer++,
        v_GrossAmount = varIncrementer++;

$(document).ready(function () {
    $('#cboCompany').select2();
    $('#cboClient').select2();
    $('#cboContract').select2();
    $('#cboPaymentMode').select2();

    $('#cboAddCollectionType').select2();
    $('#cboCompany').focus();
});

function fn_GetSearchResult(p_vTrack, p_objResult) {
    if (p_vTrack == "0") {
        callBack('GetSearchResult', 'cboCompany@cboContract@cboClient@cboPaymentMode@txtContractNo@txtInvoiceNo@txtInvoiceStartDate@txtInvoiceEndDate@txtReceivableStartDate@txtReceivableEndDate');
    }
    else {
        document.getElementById("divResult").innerHTML = p_objResult.grdResult;
    }
    return false;
}

function ShowEditDiv(objID, objControl) {
    Page_ClientValidate('');

    //For Edit
    if (objID != 0) {
        var varRow = objControl.parentNode.parentNode;
        document.getElementById('hdnCollectionID').value = varRow.cells[v_CollectionID].innerText;
        document.getElementById('hdnInvoiceID').value = varRow.cells[v_InvoiceID].innerText;

        $('#divInsertEdit').dialog('open');
        $('#divinsertedit').dialog("option", "title", 'edit collection for [collection # ' + varRow.cells[v_CollectionNo].innerText + ']');
        var vAdditionalTrack = "RowID@@" + varRow.cells[v_Sr].innerText + "~~txtAddInvoiceNo@@" + varRow.cells[v_InvoiceNo].innerText + "~~Flag@@Edit";
        callBack('AddRecord', '', vAdditionalTrack);
    }
    else {//For Insert
        document.getElementById('hdnInvoiceID').value = "0";
        document.getElementById('hdnCollectionID').value = "0";
        $('#divInsertEdit').dialog('open');
        fn_ClearControls(2);

        $('#divInsertEdit').dialog("option", "title", 'Add Collection');
    }
}

function fn_EdiRecord_Res(objResult) {
    var varRow = document.getElementById('grdResult').rows[objResult.RowID];

    $('#txtAddContractPer').focus();
    document.getElementById("cboAddClient").innerHTML = objResult.cboAddClient;
    $('#cboAddClient').select2();

    document.getElementById("cboAddContract").innerHTML = objResult.cboAddContract;
    $('#cboAddContract').select2();
    document.getElementById("cboAddTrnContract").innerHTML = objResult.cboAddTrnContract;
    $('#cboAddTrnContract').select2();

    $('#cboAddCompany').val(varRow.cells[v_CompanyID].innerText);
    $('#cboAddClient').val(varRow.cells[v_ClientID].innerText);
    $('#cboAddContract').val(varRow.cells[v_ContractID].innerText);
    $('#cboAddTrnContract').val(varRow.cells[v_TrnContractID].innerText);
    $('#hdnPaymentLevelID').val(varRow.cells[v_PaymentLevelID].innerText);

    $('#lblPaymentMode').html(varRow.cells[v_PaymentModeName].innerText);
    $('#lblPaymentLevel').html(varRow.cells[v_PaymentLevelID].innerText);

    $('#txtAddInvoiceDate').val(varRow.cells[v_InvoiceDate].innerText);
    $('#txtAddContractPer').val(varRow.cells[v_PaymentLevelPer].innerText);
    $('#txtGrossInvoiceAmt').val(varRow.cells[v_GrossInvoiceAmount].innerText);
    $('#txtAddServiceTaxPer').val(varRow.cells[v_ServiceTaxPer].innerText);
    $('#txtServiceTaxAmt').val(varRow.cells[v_ServiceTaxAmount].innerText);
    $('#txtFinalInvoiceAmt').val(varRow.cells[v_FinalInvoiceAmount].innerText);

    $('#lblContractAmount').html(objResult.lblContractAmount);

    document.getElementById('hdnCompletedContractPer').value = (parseFloat(objResult.hdnCompletedContractPer) - parseFloat(varRow.cells[v_PaymentLevelPer].innerText));
    document.getElementById('hdnMaxContractInvoice').value = objResult.hdnMaxContractInvoice;
    document.getElementById('hdnCompletedInvAmount').value = (parseFloat(objResult.hdnCompletedInvAmount) - parseFloat(varRow.cells[v_GrossInvoiceAmount].innerText));

    document.getElementById('cboAddCompany').disabled = true;
    document.getElementById('cboAddClient').disabled = true;
    document.getElementById('cboAddContract').disabled = true;
    document.getElementById('cboAddTrnContract').disabled = true;

}

function fn_AddRecord_res(objResult) {
    if (objResult.Flag == "1") {
        show_globalMessage("Invalid invoice number.", 'error');
    }
    else if (objResult.Flag == "2") {
        show_globalMessage("Payment for invoice is already done.", 'error');
    }
    else if (objResult.Flag == "3") {
        document.getElementById("lblAddCompany").innerText = objResult.lblAddCompany;

        document.getElementById("lblAddClient").innerText = objResult.lblAddClient;
        document.getElementById("lblAddContract").innerText = objResult.lblAddContract;
        document.getElementById("lblAddPaymentMode").innerText = objResult.lblAddPaymentMode;
        document.getElementById("lblPaymentLevel").innerText = objResult.lblPaymentLevel;
        document.getElementById("lblAddGrossAmount").innerText = objResult.txtAddAmount.replace(',', '');
        document.getElementById("txtAddAmount").value = objResult.txtAddAmount.replace(',', '');
        document.getElementById('hdnInvoiceID').value = objResult.hdnInvoiceID;
        if (objResult.RowID != undefined) {
            var varRow = document.getElementById('grdResult').rows[objResult.RowID];

            $('#txtAddInvoiceNo').val(varRow.cells[v_InvoiceNo].innerText);
            $('#txtAddCollectionDate').val(varRow.cells[v_CollectionDate].innerText);
            $("#cboAddCollectionType").select2("val", varRow.cells[v_CollectionType].innerText);
            $('#txtAddDrawnOnBank').val(varRow.cells[v_DrawnOnBank].innerText);
            $('#txtAddRefNo').val(varRow.cells[v_RefNo].innerText);

            $('#txtAddAmount').val(varRow.cells[v_Amount].innerText.replace(',', ''));
            if (varRow.cells[v_TDSAmount].innerText == "-") {
                $('.radio1').attr('checked', true);
                $('#rbTDSReceivedYes').attr('checked', false);
                $('#rbTDSReceivedNo').attr('checked', true);
                $('#txtTDSAmount').val("");
                $("#txtAddTDSAmount").attr('disabled', true); 
            }
            else {
                $('#rbTDSReceivedYes').attr('checked', true);
                $('#rbTDSReceivedNo').attr('checked', false);
                $('#txtTDSAmount').val(varRow.cells[v_TDSAmount].innerText.replace(',', ''));
                $("#txtAddTDSAmount").attr('disabled', false);
                $('#txtAddTDSAmount').val(varRow.cells[v_TDSAmount].innerText.replace(',', '')); 
            }
            fn_CalculateGross();

            $('#txtAddRemarks').html(varRow.cells[v_Remarks].innerText);

        }
    }

}

function fn_ClearControls(varFlag) {
    if (varFlag == 1 || varFlag == 2) {
        var varControls = "lblAddClient,lblAddPaymentMode,lblAddCompany,lblAddContract,lblPaymentLevel".split(',');
        varControls.forEach(function (cntr) {
            document.getElementById(cntr).innerText = "";
        });
    }
    if (varFlag == 2) {
        var varControls = "txtAddInvoiceNo,txtAddCollectionDate,txtAddDrawnOnBank,txtAddRefNo,txtAddAmount,txtAddTDSAmount,txtAddRemarks".split(',');
        varControls.forEach(function (cntr) {
            document.getElementById(cntr).value = "";
        });
        document.getElementById('cboAddCollectionType').value = "0";
        $('input[name=rbTDSReceivedYes]').attr('checked', false);
        document.getElementById('lblAddGrossAmount').innerText = "";
    }
}

function fn_SaveDetails() {

    if (Page_ClientValidate("vgSave")) {
        $('#btnSave').attr('disabled', true);
        vControlList = "txtAddInvoiceNo@txtAddCollectionDate@cboAddCollectionType@txtAddDrawnOnBank@txtAddRefNo@txtAddAmount@txtAddTDSAmount@txtAddRemarks";
        vControlList += "@cboCompany@cboContract@cboClient@cboPaymentMode@txtContractNo@txtInvoiceNo@txtInvoiceStartDate@txtInvoiceEndDate@txtReceivableStartDate@txtReceivableEndDate";

        var vAdditionalTrack = "InvoiceID@@" + document.getElementById('hdnInvoiceID').value;
        vAdditionalTrack += "~~CollectionID@@" + document.getElementById('hdnCollectionID').value;
        vAdditionalTrack += "~~TDSDeducted@@" + ($('#rbTDSReceivedYes').is(':checked') ? "1" : "0");

        callBack('InsertEditDetails', vControlList, vAdditionalTrack);
        $('#divInsertEdit').dialog('close');
    }
    $('#btnSave').attr('disabled', false);

    return;
}
function fn_ValidateTDSTax(sender, args) {
    args.IsValid = true;
    if (!$('#rbTDSReceivedYes').is(':checked') && !$('#rbTDSReceivedNo').is(':checked'))
        args.IsValid = false;
    return args.IsValid;
}
function fn_ValidateTDSAmount(sender, args) {
    var vTDSDeducted = (($('#rbTDSReceivedYes').is(':checked')) ? "1" : "0");
    args.IsValid = true;
    if (vTDSDeducted == "1") {
        if ($("#txtAddTDSAmount").val() == "") {
            args.IsValid = false;
        }
    }
}

function fn_ValidateValues(objFlag) {
    if (document.getElementById('cboAddTrnContract') != '') {
        if (objFlag == "ContractPer") {
            var varContractPer = (document.getElementById("txtAddContractPer").value == "" ? 0 : parseFloat(document.getElementById("txtAddContractPer").value));
            if (varContractPer > 0) {
                var varTotContractInv = parseFloat(document.getElementById("lblContractAmount").innerText);
                var varInvAmount = Math.round(varTotContractInv * varContractPer / 100, 2);
                var varServiceTaxPer = parseFloat(document.getElementById("txtAddServiceTaxPer").value);
                var varServTaxAmt = Math.round(varServiceTaxPer > 0 ? varInvAmount * varServiceTaxPer / 100 : 0, 2);
                document.getElementById("txtGrossInvoiceAmt").value = varInvAmount;
                document.getElementById("txtServiceTaxAmt").value = varServTaxAmt;
                document.getElementById("txtFinalInvoiceAmt").value = (varInvAmount + varServTaxAmt);
            }
        }
        else if (objFlag == "GrossInvAmt") {
            var varGrossAmt = (document.getElementById("txtGrossInvoiceAmt").value == "" ? 0 : parseFloat(document.getElementById("txtGrossInvoiceAmt").value));
            if (varGrossAmt > 0) {
                var varTotContractInv = parseFloat(document.getElementById("lblContractAmount").innerText);
                var varContractPer = Math.round(varGrossAmt / varTotContractInv * 100, 2);
                var varServiceTaxPer = parseFloat(document.getElementById("txtAddServiceTaxPer").value);
                var varServTaxAmt = Math.round(varServiceTaxPer > 0 ? varGrossAmt * varServiceTaxPer / 100 : 0, 2);
                document.getElementById("txtAddContractPer").value = varContractPer;
                document.getElementById("txtServiceTaxAmt").value = varServTaxAmt;
                document.getElementById("txtFinalInvoiceAmt").value = (varGrossAmt + varServTaxAmt);
            }
        }
        else if (objFlag == "ContractPer") {
            var varContractPer = (document.getElementById("txtAddContractPer").value == "" ? 0 : parseFloat(document.getElementById("txtAddContractPer").value));
            if (varContractPer > 0) {
                var varGrossAmt = (document.getElementById("txtGrossInvoiceAmt").value == "" ? 0 : parseFloat(document.getElementById("txtGrossInvoiceAmt").value));
                var varServTaxAmt = Math.round(varContractPer > 0 ? varGrossAmt * varContractPer / 100 : 0, 2);
                document.getElementById("txtServiceTaxAmt").value = varServTaxAmt;
                document.getElementById("txtFinalInvoiceAmt").value = (varGrossAmt + varServTaxAmt);
            }
        }
    }
}

/**** Regular Expression Validator *****/
function fn_RegExpValidator(p_obj, p_args) {
    p_args.IsValid = true;
    var varCntl = $("#" + p_obj.controltovalidate);
    if (varCntl.attr("type") == "text") {
        if (varCntl.val() != "") {
            var vValidation = fn_ValidateExpression(varCntl.val(), $(p_obj).attr("expressionid"));
            if (vValidation != "") {
                args.IsValid = false;
                sender.childNodes['0'].innerHTML = vValidation;
            }
        }
    }
    return p_args.IsValid;
}

function getResponse(returnVal) {
    try {
        hideLoader(returnVal);
        var objResult = $.parseJSON(returnVal);
        if (objResult.SessionTimeOut == "1") {
            window.location.href = 'login.aspx';
        }
        else {
            var varTrack = objResult.Track;

            if (objResult.Track == "GetSearchResult") {
                fn_GetSearchResult("1", objResult);
            }
            else if (objResult.Track == "DeleteRecord") {
                if (objResult.IsSuccess == "1") {
                    show_globalMessage(objResult.strMessage, 'info');
                    fn_GetSearchResult("1", objResult);
                }
                else if (objResult.IsSuccess == "0") {
                    show_globalMessage(objResult.strMessage, 'error');
                }
                else {
                    show_globalMessage(objResult.strMessage, 'error');
                }
            }
            else if (objResult.Track == "InsertEditDetails") {
                if (objResult.IsSuccess == "1") {
                    if (parseInt($('#hdnContractID').val()) > 0)
                        show_globalMessage(objResult.strUpdateMessage, 'info');
                    else
                        show_globalMessage(objResult.strSaveMessage, 'info');
                    fn_GetSearchResult("1", objResult);
                }

                else if (objResult.IsSuccess == "0") {
                    show_globalMessage(objResult.strMessage, 'error');
                }
                else {
                    show_globalMessage(objResult.strMessage, 'error');
                }
            }
            if (objResult.Track == "EdiRecord") {
                fn_EdiRecord_Res(objResult);
            }
            if (objResult.Track == "AddRecord") {
                fn_AddRecord_res(objResult);
            }
        }
    }
    catch (ex) {
        show_globalMessage('Error', 'error');
    }
}

function fn_ExportToExcel() {//http://docs.dhtmlx.com/grid__data_export.html
    window.open('data:application/vnd.ms-excel,' + $('#divResult div').html());

    // grid.toExcel($('#hdnExportToExcelFilePath').val());
}

function fn_ChangeViewTDS() {
    if ($('#rbTDSReceivedYes').is(':checked')) {
        $("#txtAddTDSAmount").attr('disabled', false);
    }
    else {
        $("#txtAddTDSAmount").attr('disabled', true);
        $("#txtAddTDSAmount").val('');
    }
    fn_CalculateGross();
    document.getElementById("cvServiceTax").style.display = "none";
}

function fn_CalculateGross() {
    var vTotAmt = parseFloat($("#txtAddAmount").val() == "" ? 0 : $("#txtAddAmount").val()) - parseFloat($("#txtAddTDSAmount").val() == "" ? 0 : $("#txtAddTDSAmount").val());
    $("#lblAddGrossAmount").html(vTotAmt);
}

function fn_ChangeInvoiceNo() {
    if (document.getElementById('txtAddInvoiceNo').value.trim() != '')
        callBack('AddRecord', "txtAddInvoiceNo", "Flag@@Add");
    else {
        fn_ClearControls(1);
    }
}

function DeleteRec(varCollectionID) {
    if (confirm("Are you sure want to delete this record ? ") == true) {
        var vControlList = "cboCompany@cboContract@cboClient@cboPaymentMode@txtContractNo@txtInvoiceNo@txtInvoiceStartDate@txtInvoiceEndDate@txtReceivableStartDate@txtReceivableEndDate";
        var vAdditionalTrack = "CollectionID@@" + varCollectionID;
        callBack('DeleteRecord', vControlList, vAdditionalTrack);
    }
}